package com.basics.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.basics.api.request.login.PhoneLoginRequest;
import com.basics.api.response.LoginData;
import com.basics.api.service.LoginApiService;
import com.basics.api.vo.UserInfo;
import com.basics.common.exception.CustomException;
import com.basics.common.utils.DateUtils;
import com.basics.common.utils.RandomUtils;
import com.basics.common.utils.SmsWhUtil;
import com.basics.common.utils.StringUtils;
import com.basics.common.utils.oss.AliOSSUtil;
import com.basics.common.utils.oss.ToolsUtil;
import com.basics.common.utils.weixin.accesstoken.WeixinGetWebAccessTokenUtil;
import com.basics.common.utils.weixin.model.accesstoken.WebAccessToken;
import com.basics.common.utils.weixin.model.user.WeixinUserInfo;
import com.basics.framework.constants.SecurityConstants;
import com.basics.framework.utils.JwtYzUtils;
import com.basics.user.entity.CyAuth;
import com.basics.user.entity.CyUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;

/**
 * @Author WangWei
 * @Date 2021/11/25 12:19
 * @Version 2.0
 * @Description
 **/
@Service
public class LoginApiServiceImpl extends BaseApiService implements LoginApiService {


    @Override
    public void getPhoneCode(String phone) {
       getPhoneCode(phone, null);
    }

    @Override
    @Transactional
    public LoginData appLogin(String code) {
        WebAccessToken webAccessToken = WeixinGetWebAccessTokenUtil.getWebAccessToken(code);
        logger.error("【app登录获取的token】:{}", JSONObject.toJSON(webAccessToken));
        if (webAccessToken != null) {
            WeixinUserInfo weixinUserInfo = WeixinGetWebAccessTokenUtil.getWeixinUserInfo(webAccessToken);
            UserInfo userInfo;
            if (weixinUserInfo != null) {
                String openId = weixinUserInfo.getOpenId();
                String nickName = weixinUserInfo.getNickName();
                String unionId = weixinUserInfo.getUnionId();

                CyUser user = cyUserService.getByOpenId(openId);
                if (user == null) {
                    user = new CyUser();
                    user.setOpenId(openId);
                    user.setUnionId(unionId);
                    user.setNickName(nickName);
                    user.setSource("app");
                    if(StringUtils.isNotEmpty(weixinUserInfo.getHeadImgUrl())){
                        InputStream is = ToolsUtil.downloadImg(weixinUserInfo.getHeadImgUrl());
                        if (is != null) {
                            user.setAvatar("https://" + AliOSSUtil.uploadInputSteam("headerImg/" + DateUtils.dateTime() + "/" + openId + ".png", is));
                        } else {
                            user.setAvatar(weixinUserInfo.getHeadImgUrl());
                        }
                    }
                    //cyUserService.save(user);
                    redisUtil.set(openId, JSONObject.toJSONString(user), 60 * 60 * 24*7 );
                    userInfo = new UserInfo();
                    userInfo.setOpenId(openId);
                    userInfo.setNickName(nickName);
                    userInfo.setAvatar(weixinUserInfo.getHeadImgUrl());
                    userInfo.setHasOrganization(false);
                } else {
                    user.setNickName(nickName);
                    if (StringUtils.isEmpty(user.getUnionId())) {
                       // user.setOpenId(openId);
                        user.setUnionId(unionId);
                    }
                    if(StringUtils.isNotEmpty(weixinUserInfo.getHeadImgUrl())){
                        InputStream is = ToolsUtil.downloadImg(weixinUserInfo.getHeadImgUrl());
                        if (!(StringUtils.isNotEmpty(user.getAvatar()) && user.getAvatar().indexOf("https://oss.dimoclub.com") != -1)) {
                            if (is != null) {
                                user.setAvatar("https://" + AliOSSUtil.uploadInputSteam("headerImg/" + DateUtils.dateTime() + "/" + openId + ".png", is));
                            } else {
                                user.setAvatar(weixinUserInfo.getHeadImgUrl());
                            }
                        }
                    }
                    cyUserService.updateById(user);
                    userInfo = getUserInfo(user);
                }
                /**
                 * 生成Token
                 */
                String jwt_token = JwtYzUtils.generateAccessToken(userInfo);
                String token = SecurityConstants.TOKEN_PREFIX + jwt_token;
                LoginData result = new LoginData();
                if(StringUtils.isNotEmpty(user.getPhone())){
                    result.setToken(token);
                }
                result.setUserInfo(userInfo);
                redisUtil.set(SecurityConstants.TOKEN_PREFIX+userInfo.getUserId(), jwt_token);
                return result;

            } else {
                throw new CustomException("获取用户信息失败");
            }
        } else {
            throw new CustomException("授权失败");
        }
    }



    @Override
    @Transactional
    public LoginData phoneLogin(PhoneLoginRequest request) {
        boolean flag = checkCode(request.getPhone(), null, request.getCode());
        if(!flag){
            throw new CustomException("验证码错误");
        }
        CyUser user;
        if(request.getOpenId()!=null){
            Object obj = redisUtil.get(request.getOpenId());
            if(obj!=null){
                user = cyUserService.getByPhone(request.getPhone());
                CyUser  opUser = JSONObject.parseObject(obj.toString(), CyUser.class);
                if(opUser!=null && StringUtils.isNotEmpty(user.getPhone())){
                    user.setOpenId(opUser.getOpenId());
                    user.setAvatar(opUser.getAvatar());
                    user.setNickName(opUser.getNickName());
                    cyUserService.updateById(user);
                }else{
                    if(opUser!=null){
                        opUser.setPhone(request.getPhone());
                        cyUserService.save(opUser);
                    }else{
                        opUser = new CyUser();
                        opUser.setPhone(request.getPhone());
                        opUser.setOpenId(request.getOpenId());
                        cyUserService.save(opUser);
                    }

                }

                redisUtil.del(request.getOpenId());
            }else{
                user = cyUserService.getByPhone(request.getPhone());
                if (user == null) {
                    /**
                     * 首次登录
                     */
                    user = new CyUser();
                    user.setSource("app");
                    user.setPhone(request.getPhone());
                    cyUserService.save(user);
                }
            }

        }else{
            user = cyUserService.getByPhone(request.getPhone());
            if (user == null) {
                /**
                 * 首次登录
                 */
                user = new CyUser();
                user.setSource("app");
                user.setPhone(request.getPhone());
                cyUserService.save(user);
            }
        }

        UserInfo userInfo = getUserInfo(user);
        /**
         * 生成Token
         */
        String jwt_token = JwtYzUtils.generateAccessToken(userInfo);
        String token = SecurityConstants.TOKEN_PREFIX + jwt_token;
        LoginData result = new LoginData();
        result.setToken(token);
        result.setUserInfo(userInfo);
        redisUtil.set(SecurityConstants.TOKEN_PREFIX +userInfo.getUserId(), jwt_token);
        return result;
    }
}
